
import * as cache from "@/utils/storage.js"
import {msgFilter} from "@/IM/msg.js"

const POOL_KEY = 'message_pools_'


let pools = {}
let userId = ''

export const resetPools = ()=>{
	pools = {}
	userId = ''
}

export const initPools = async (id) =>{
	userId = id
	const poolData = await cache.get(`${POOL_KEY}${userId}`)||{}
	Object.entries(poolData).forEach(([key,value])=>{
		pools[key] = value
	})
}

const getTenLastSuccess = (list=[]) =>{
	const arr = []
	for (let i = list.length-1; i >=0; i--) {
		let item = list[i]
		if(item.status=='loading'||item.status=='error'){
			continue
		}
		arr.unshift({...msgFilter(item),avatar:item.avatar,nick:item.nick,createTime:item.createTime})
		if(arr.length>=10){
			return arr
		}
	}
	return arr
}

export const savePools = async () =>{
	const poolData = Object.entries(pools).reduce((r,[key,msgList])=>{
		r[key] = getTenLastSuccess(msgList)
		return r
	},{})
	await cache.set(`${POOL_KEY}${userId}`,poolData)
}



export const getPool = (id)=>{
	let pool = pools[id]
	if(!pool){
		pool = []
		pools[id] = pool
	}
	return pool
}
// #ifdef H5
window.pools = pools
// #endif
